package cn.lg.soar.boot.client.service.impl;

import cn.lg.soar.boot.client.entity.Applicant;
import cn.lg.soar.boot.client.entity.ClientUser;
import cn.lg.soar.boot.client.entity.vo.ClientUserVo;
import cn.lg.soar.boot.client.mapper.ClientUserMapper;
import cn.lg.soar.boot.client.service.ApplicantService;
import cn.lg.soar.boot.client.service.ClientApiService;
import cn.lg.soar.boot.client.service.ClientUserService;
import cn.lg.soar.boot.client.utils.JWTUtil;
import cn.lg.soar.boot.fc.entity.*;
import cn.lg.soar.boot.fc.entity.Process;
import cn.lg.soar.boot.fc.entity.vo.*;
import cn.lg.soar.boot.fc.service.*;
import cn.lg.soar.common.data.msg.I18n;
import cn.lg.soar.common.model.HttpResult;
import cn.lg.soar.common.model.PageQuery;
import cn.lg.soar.common.model.PageResult;
import cn.lg.soar.common.util.AssertUtil;
import cn.lg.soar.database.base.service.impl.BaseServiceImpl;
import cn.lg.soar.database.query.QueryParams;
import cn.lg.soar.database.query.SqueryWapper;
import cn.lg.soar.system.auth.entity.Org;
import cn.lg.soar.system.auth.entity.User;
import cn.lg.soar.system.auth.service.IOrgService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.security.SecureRandom;
import java.time.LocalDateTime;
import java.util.*;

/**
 * 用户信息表
 * @author ZhuanZ（无密码）
 * @since 2025-02-13
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
@Service
public class ClientApiServiceImpl extends BaseServiceImpl<ClientUserMapper, ClientUser> implements ClientApiService {

    protected final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Resource
    private IOrgService orgService;
    @Resource
    private TenancyRoomService tenancyRoomService;
    @Resource
    private RoomService roomService;
    /** 客户端用户信息服务 */
    @Resource private ClientUserService clientUserService;
    @Resource
    private FormItemService formItemService;
    @Resource
    protected FormCollectService formCollectService;
    @Resource
    private FormResultService formResultService;
    @Resource
    protected ProcessService processService;
    @Resource
    private ProcessApplyService processApplyService;
    @Resource
    private TenancyRoomRecordService tenancyRoomRecordService;
    @Resource
    private RepairService repairService;
    @Resource
    private ContractService contractService;
    @Autowired
    private ApplicantService applicantService;

    /**
     * 用户登录
     * @param account
     * @param password
     */
    @Transactional
    public HttpResult<Object> signin(String account, String password) {
        logger.info("[开始]用户登录处理");

        // =============================
        // 验证用户账号是否存在
        // =============================
        ClientUser user = clientUserService.selectByAccount(account);
        if (user == null) {
            logger.warn("\t账号信息不存在", account);
            return HttpResult.fail("B0000", I18n.build("账号信息不存在"));
        }

//        String salt = randomSalt();
//        SimpleHash hash = new SimpleHash("md5", "123456", salt, 2);
//        user.setSalt(salt);                                          // 密码盐
//        user.setPassword(hash.toHex());                              // 登录密码

        // =============================
        // 登录密码验证
        // =============================
        SimpleHash hash = null;
        if (StringUtils.isNotEmpty(password)) {
            hash = new SimpleHash("md5", password, user.getSalt(), 2);
        } else {
            logger.warn("\t账号密码错误,请重新输入", account);
            return HttpResult.fail("B0000", I18n.build("账号密码错误,请重新输入"));
        }
        String encryPwd = hash.toHex();
        if(!encryPwd.equals(user.getPassword())) {
            logger.warn("\t账号密码错误,请重新输入", account);
            return HttpResult.fail("B0000", I18n.build("账号密码错误,请重新输入"));
        }


        // =============================
        // 更新登录用户令牌
        // =============================
//        String token = genToken();
        String token = JWTUtil.sign(user);
        user.setToken(token);                             // 访问令牌
        AssertUtil.isTrue(super.updateById(user), "更新失败");

//        ShiroUtils.getSession().setAttribute(user.getId(), token);
//        ShiroUtils.getSession().setTimeout(1200000);
        Map map = new HashMap();
        map.put("token", token);

        logger.info("[完成]用户登录处理");
        return HttpResult.success("登录成功", map);
    }

    /**
     * 获取用户信息
     * @param token
     */
    @Transactional
    public HttpResult<ClientUserVo> userInfo(String token) {
        ClientUser record = clientUserService.selectByToken(token);
        ClientUserVo vo = new ClientUserVo();
        BeanUtils.copyProperties(record, vo);
        if(record.getOrgId() != null){
            Org org = orgService.getById(record.getOrgId());
            if(org != null){
                vo.setOrgName(org.getName());
            }
        }
        return HttpResult.data(vo);
    }

    /**
     * 刷新token
     * @param token
     */
    @Transactional
    public HttpResult<Object> refreshToken(String token) {
        logger.info("[开始]刷新token");

        ClientUser user = clientUserService.selectByToken(token);
        if (user == null) {
            logger.warn("\t账号信息不存在", token);
            return HttpResult.fail("B0000", I18n.build("账号信息不存在"));
        }

        // =============================
        // 更新登录用户令牌
        // =============================
//        String newToken = genToken();
        String newToken = JWTUtil.sign(user);
        user.setToken(newToken);                          // 访问令牌
        AssertUtil.isTrue(super.updateById(user), "更新失败");

        Map map = new HashMap();
        map.put("token", newToken);

        logger.info("[完成]刷新token处理");
        return HttpResult.success("刷新token成功", map);
    }

    /**
     * 获取我的房源
     */
    @Transactional
    public HttpResult<PageResult<TenancyRoomVo>> housingList(PageQuery pageQuery, String token, Integer housingType){
        ClientUser user1 = clientUserService.selectByToken(token);
        if (user1 == null) {
            logger.warn("\t账号信息不存在", token);
            return HttpResult.fail("B0000", I18n.build("账号信息不存在"));
        }
        SqueryWapper<TenancyRoom> squeryWapper = new SqueryWapper<>(TenancyRoom.class);
        QueryParams params = new QueryParams();
        List<String > f = new ArrayList<>();
        f.add("userId-eq~"+user1.getId());
        if(housingType == 0){
            f.add("tenancyState-ne~5");
        }else{
            f.add("tenancyState-eq~5");
        }
        params.setF(f);

        PageResult<TenancyRoomVo> pageResult = new PageResult<>();
        List<TenancyRoomVo> list = new ArrayList<>();
        List<TenancyRoom> tenancyRoomQuery = squeryWapper.query(tenancyRoomService, pageQuery, params).getList();
        for (TenancyRoom tenancyRoom : tenancyRoomQuery) {
            TenancyRoomVo tenancyRoomVo = new TenancyRoomVo();
            BeanUtils.copyProperties(tenancyRoom, tenancyRoomVo);
            RoomVo roomVo = roomService.getVoData(tenancyRoom.getRoomId());
            String roomInfo = "";
            if(roomVo != null) {
                roomInfo = roomVo.getCampusEasyVo().getName()+"*"+roomVo.getBuildingEasyVo().getName()+"*"+roomVo.getUnitEasyVo().getName()+"*"
                        +roomVo.getFloorEasyVo().getName()+"*"+roomVo.getRoomCode();
            }
            tenancyRoomVo.setRoomInfo(roomInfo);

//            User user = userService.getById(tenancyRoom.getUserId());
            ClientUser user = clientUserService.getById(tenancyRoom.getUserId());
            if(user != null) {
                tenancyRoomVo.setUserName(user.getUserName());
            }
            tenancyRoomVo.setArea(roomVo.getArea());
            tenancyRoomVo.setLivingRoom(roomVo.getLivingRoom());
            tenancyRoomVo.setOrient(roomVo.getOrient());
            tenancyRoomVo.setOwnershipCode(roomVo.getOwnershipCode());
            tenancyRoomVo.setContacts(roomVo.getContacts());
            tenancyRoomVo.setPhone(roomVo.getPhone());
            list.add(tenancyRoomVo);
        }
        pageResult.setList(list);
        return HttpResult.data(pageResult);
    }

    /**
     * 房源详情
     */
    @Transactional
    public HttpResult<TenancyRoomVo> tenancyRoomInfo(Long tenancyRoomId) {
        TenancyRoom tenancyRoom = tenancyRoomService.getData(tenancyRoomId);
        TenancyRoomVo tenancyRoomVo = new TenancyRoomVo();
        BeanUtils.copyProperties(tenancyRoom, tenancyRoomVo);
        RoomVo roomVo = roomService.getVoData(tenancyRoom.getRoomId());
        String roomInfo = roomVo.getCampusEasyVo().getName()+"*"+roomVo.getBuildingEasyVo().getName()+"*"+roomVo.getUnitEasyVo().getName()+"*"
                +roomVo.getFloorEasyVo().getName()+"*"+roomVo.getRoomCode();
        tenancyRoomVo.setRoomInfo(roomInfo);

        ClientUser user = clientUserService.getById(tenancyRoom.getUserId());
        if(user != null) {
            tenancyRoomVo.setUserName(user.getUserName());
        }
        tenancyRoomVo.setArea(roomVo.getArea());
        tenancyRoomVo.setLivingRoom(roomVo.getLivingRoom());
        tenancyRoomVo.setOrient(roomVo.getOrient());
        tenancyRoomVo.setOwnershipCode(roomVo.getOwnershipCode());
        tenancyRoomVo.setContacts(roomVo.getContacts());
        tenancyRoomVo.setPhone(roomVo.getPhone());
        return HttpResult.data(tenancyRoomVo);
    }

    /**
     * 获取表单
     */
    @Transactional
    public HttpResult<List<FormItem>> formItem(Integer visibleRange) {
        SqueryWapper squeryWapperCollect = new SqueryWapper<>(FormCollect.class);
        QueryWrapper<FormCollect> wrapper = Wrappers.query();
        List<String> f1 = new ArrayList<>();
        f1.add("visibleRange-eq~"+visibleRange);
        squeryWapperCollect.setWhere(f1, wrapper);
        List<FormCollect> list = formCollectService.list(wrapper);
        if(list.size() <= 0){
            return HttpResult.fail("B0000", I18n.build("租房申请表单为空！"));
        }

        SqueryWapper squeryWapperFormItem = new SqueryWapper<>(FormItem.class);
        QueryWrapper<FormItem> wrapperFormItem = Wrappers.query();
        List<String> f = new ArrayList<>();
        f.add("collectId-eq~"+list.get(0).getId());
        List<String> orderBy = new ArrayList<>();
        orderBy.add("sort");
        squeryWapperFormItem.setWhere(f, wrapperFormItem);
        squeryWapperFormItem.setOrderBy(orderBy, wrapperFormItem);
        return HttpResult.data(formItemService.list(wrapperFormItem));
    }

    /**
     * 申请租房
     */
    @Transactional
    public HttpResult<Void> applyRoom(String token,Long applicantId,Long collectId,Long roomId,String processData) {
        ClientUser user = clientUserService.selectByToken(token);
        if (user == null) {
            logger.warn("\t账号信息不存在", token);
            return HttpResult.fail("B0000", I18n.build("账号信息不存在"));
        }
        Applicant applicant = applicantService.getById(applicantId);
        if(applicant == null) {
            return HttpResult.fail("B0000", I18n.build("申请人为空！"));
        }
        List formContentConfigList = new ArrayList();
        SqueryWapper squeryWapper = new SqueryWapper<>(FormItem.class);
        QueryWrapper<FormItem> wrapper = Wrappers.query();
        List<String> f = new ArrayList<>();
        f.add("collectId-eq~"+collectId);
        List<String> orderBy = new ArrayList<>();
        orderBy.add("sort");
        squeryWapper.setWhere(f, wrapper);
        squeryWapper.setOrderBy(orderBy, wrapper);
        List<FormItem> list1 = formItemService.list(wrapper);
        for (FormItem item : list1) {
            formContentConfigList.add(item.getFormItemConfig());
        }

        FormResult formResult = new FormResult();
        formResult.setCollectId(collectId);
        formResult.setSubmitApplicantId(applicantId);
        formResult.setSubmitUserId(user.getId());
        formResult.setProcessData(processData);
        formResult.setFormContentConfig(formContentConfigList.toString());
        formResultService.submitForm(formResult,roomId,null);
        return HttpResult.success();
    }

    /**
     * 用户房源记录
     */
    @Transactional
    public HttpResult<PageResult<HousingRecordVo>> housingRecord(PageQuery pageQuery, String token) {
        ClientUser user = clientUserService.selectByToken(token);
        if (user == null) {
            logger.warn("\t账号信息不存在", token);
            return HttpResult.fail("B0000", I18n.build("账号信息不存在"));
        }
        PageResult<HousingRecordVo> pageResult = new PageResult<>();
        SqueryWapper processWapper = new SqueryWapper<>(cn.lg.soar.boot.fc.entity.Process.class);
        QueryWrapper<cn.lg.soar.boot.fc.entity.Process> processWrapper = Wrappers.query();
        List<String> f0 = new ArrayList<>();
        f0.add("examineType-eq~1");
        processWapper.setWhere(f0, processWrapper);
        List<cn.lg.soar.boot.fc.entity.Process> processList = processService.list(processWrapper);
        if(!processList.isEmpty()){
            String[] processIds = new String[processList.size()];
            for (int i=0;i<processList.size();i++) {
                processIds[i] = String.valueOf(processList.get(i).getId());
            }
            QueryParams params = new QueryParams();
            List<String > f1 = new ArrayList<>();
            f1.add("applicantId-eq~"+user.getId());
            f1.add("processId-in~"+ Arrays.toString(processIds).substring(1, Arrays.toString(processIds).length() - 1).replaceAll(",","~"));
            params.setF(f1);
            List<HousingRecordVo> list = new ArrayList<>();
            SqueryWapper<ProcessApply> squeryWapper = new SqueryWapper<>(ProcessApply.class);
            List<ProcessApply> processApplyQuery = squeryWapper.query(processApplyService, pageQuery, params).getList();
            for (ProcessApply apply : processApplyQuery) {
                HousingRecordVo recordVo = new HousingRecordVo();
                BeanUtils.copyProperties(apply, recordVo);
                SqueryWapper tenancyRoomWapper = new SqueryWapper<>(TenancyRoom.class);
                QueryWrapper<TenancyRoom> wrapper = Wrappers.query();
                List<String> f = new ArrayList<>();
                f.add("formApplyId-eq~"+apply.getId());
                tenancyRoomWapper.setWhere(f, wrapper);
                List<TenancyRoom> tenancyRoomList = tenancyRoomService.list(wrapper);
                if(!tenancyRoomList.isEmpty()){
                    TenancyRoom tenancyRoom = tenancyRoomList.get(0);
                    RoomVo roomVo = roomService.getVoData(tenancyRoom.getRoomId());
                    String roomInfo = roomVo.getCampusEasyVo().getName()+"*"+roomVo.getBuildingEasyVo().getName()+"*"+roomVo.getUnitEasyVo().getName()+"*"
                            +roomVo.getFloorEasyVo().getName()+"*"+roomVo.getRoomCode();
                    recordVo.setRoomInfo(roomInfo);
                    recordVo.setArea(roomVo.getArea());
                    recordVo.setLivingRoom(roomVo.getLivingRoom());
                    recordVo.setOrient(roomVo.getOrient());
                    recordVo.setOwnershipCode(roomVo.getOwnershipCode());
                    recordVo.setContacts(roomVo.getContacts());
                    recordVo.setPhone(roomVo.getPhone());
                    list.add(recordVo);
                }
            }
            pageResult.setList(list);
        }

        return HttpResult.data(pageResult);
    }

    /**
     * 续租申请
     */
    @Transactional
    public HttpResult<Void> continueApply(String token,Long tenancyId) {
        ClientUser user = clientUserService.selectByToken(token);
        if (user == null) {
            logger.warn("\t账号信息不存在", token);
            return HttpResult.fail("B0000", I18n.build("账号信息不存在"));
        }
        // 更新租房情况
        TenancyRoom tenancyRoom = tenancyRoomService.getById(tenancyId);
        if (null == tenancyRoom){
            return HttpResult.fail("B0000", I18n.build("租房信息为空！"));
        }
        if(user.getId() != tenancyRoom.getUserId()){
            logger.warn("\t租房信息与用户信息不匹配", token);
            return HttpResult.fail("B0000", I18n.build("租房信息与用户信息不匹配"));
        }
        Room room = roomService.getById(tenancyRoom.getRoomId());
        if(room != null){
//            tenancyRoom.setWaitPay(room.getRent());
//            tenancyRoom.setContinuePay(room.getRent());
            tenancyRoom.setWaitPay(new BigDecimal(500));
            tenancyRoom.setContinuePay(new BigDecimal(500));
        }
        tenancyRoom.setContinueState(2);
        tenancyRoom.setContinueTime(LocalDateTime.now());
        AssertUtil.isTrue(tenancyRoomService.updateById(tenancyRoom), "更新失败");
        return HttpResult.success();
    }

    /**
     * 用户续租记录
     */
    @Transactional
    public HttpResult<PageResult<HousingRecordVo>> continueRecord(PageQuery pageQuery, String token) {
        ClientUser user = clientUserService.selectByToken(token);
        if (user == null) {
            logger.warn("\t账号信息不存在", token);
            return HttpResult.fail("B0000", I18n.build("账号信息不存在"));
        }
        QueryParams params = new QueryParams();
        List<String > f = new ArrayList<>();
        f.add("userId-eq~"+user.getId());
        f.add("isContinue-eq~1");
        params.setF(f);
        PageResult<HousingRecordVo> pageResult = new PageResult<>();
        List<HousingRecordVo> list = new ArrayList<>();
        SqueryWapper<TenancyRoomRecord> squeryWapper = new SqueryWapper<>(TenancyRoomRecord.class);
        List<TenancyRoomRecord> tenancyRoomRecordQuery = squeryWapper.query(tenancyRoomRecordService, pageQuery, params).getList();
        for (TenancyRoomRecord record : tenancyRoomRecordQuery) {
            HousingRecordVo recordVo = new HousingRecordVo();
            recordVo.setApplicantId(record.getUserId());
            recordVo.setApplicantName(user.getUserName());
            recordVo.setApplyTime(record.getApplyTime());
            recordVo.setResult(1);
            RoomVo roomVo = roomService.getVoData(record.getRoomId());
            String roomInfo = roomVo.getCampusEasyVo().getName()+"*"+roomVo.getBuildingEasyVo().getName()+"*"+roomVo.getUnitEasyVo().getName()+"*"
                    +roomVo.getFloorEasyVo().getName()+"*"+roomVo.getRoomCode();
            recordVo.setRoomInfo(roomInfo);
            recordVo.setArea(roomVo.getArea());
            recordVo.setLivingRoom(roomVo.getLivingRoom());
            recordVo.setOrient(roomVo.getOrient());
            recordVo.setOwnershipCode(roomVo.getOwnershipCode());
            recordVo.setContacts(roomVo.getContacts());
            recordVo.setPhone(roomVo.getPhone());
            list.add(recordVo);
        }
        pageResult.setList(list);
        return HttpResult.data(pageResult);
    }

    /**
     * 退租申请
     */
    @Transactional
    public HttpResult<Void> exitTenancyApply(String token,Long tenancyId) {
        ClientUser user = clientUserService.selectByToken(token);
        if (user == null) {
            logger.warn("\t账号信息不存在", token);
            return HttpResult.fail("B0000", I18n.build("账号信息不存在"));
        }
        // 更新租房情况
        TenancyRoom tenancyRoom = tenancyRoomService.getById(tenancyId);
        if (null == tenancyRoom){
            return HttpResult.fail("B0000", I18n.build("租房信息为空！"));
        }
        if(user.getId() != tenancyRoom.getUserId()){
            logger.warn("\t租房信息与用户信息不匹配", token);
            return HttpResult.fail("B0000", I18n.build("租房信息与用户信息不匹配"));
        }

        SqueryWapper squeryWapperProcess = new SqueryWapper<>(Process.class);
        QueryWrapper<Process> wrapper = Wrappers.query();
        List<String> f = new ArrayList<>();
        f.add("examineType-eq~2");
        squeryWapperProcess.setWhere(f, wrapper);
        List<Process> list = processService.list(wrapper);
        if(list.size() <= 0){
            System.out.println("===============1退房审批流程为空！");
            return HttpResult.fail("B0000", I18n.build("退房审批流程为空！"));
        }

        ProcessApply apply = new ProcessApply();
        apply.setTenancyRoomId(tenancyRoom.getId());
        apply.setUserId(user.getId());
        apply.setUserName(user.getUserName());
        apply.setProcessId(list.get(0).getId());
        apply.setProcessName(list.get(0).getProcessName());
        return processApplyService.applyExamine(apply);
    }

    /**
     * 用户退租记录
     */
    @Transactional
    public HttpResult<PageResult<HousingRecordVo>> exitTenancyRecord(PageQuery pageQuery, String token) {
        ClientUser user = clientUserService.selectByToken(token);
        if (user == null) {
            logger.warn("\t账号信息不存在", token);
            return HttpResult.fail("B0000", I18n.build("账号信息不存在"));
        }
        PageResult<HousingRecordVo> pageResult = new PageResult<>();
        SqueryWapper processWapper = new SqueryWapper<>(cn.lg.soar.boot.fc.entity.Process.class);
        QueryWrapper<cn.lg.soar.boot.fc.entity.Process> processWrapper = Wrappers.query();
        List<String> f0 = new ArrayList<>();
        f0.add("examineType-eq~2");
        processWapper.setWhere(f0, processWrapper);
        List<cn.lg.soar.boot.fc.entity.Process> processList = processService.list(processWrapper);
        if(!processList.isEmpty()){
            String[] processIds = new String[processList.size()];
            for (int i=0;i<processList.size();i++) {
                processIds[i] = String.valueOf(processList.get(i).getId());
            }
            QueryParams params = new QueryParams();
            List<String > f1 = new ArrayList<>();
            f1.add("applicantId-eq~"+user.getId());
            f1.add("processId-in~"+ Arrays.toString(processIds).substring(1, Arrays.toString(processIds).length() - 1).replaceAll(",","~"));
            params.setF(f1);
            List<HousingRecordVo> list = new ArrayList<>();
            SqueryWapper<ProcessApply> squeryWapper = new SqueryWapper<>(ProcessApply.class);
            List<ProcessApply> processApplyQuery = squeryWapper.query(processApplyService, pageQuery, params).getList();
            for (ProcessApply apply : processApplyQuery) {
                HousingRecordVo recordVo = new HousingRecordVo();
                BeanUtils.copyProperties(apply, recordVo);
                SqueryWapper tenancyRoomWapper = new SqueryWapper<>(TenancyRoom.class);
                QueryWrapper<TenancyRoom> wrapper = Wrappers.query();
                List<String> f = new ArrayList<>();
                f.add("formApplyId-eq~"+apply.getId());
                tenancyRoomWapper.setWhere(f, wrapper);
                List<TenancyRoom> tenancyRoomList = tenancyRoomService.list(wrapper);
                if(!tenancyRoomList.isEmpty()){
                    TenancyRoom tenancyRoom = tenancyRoomList.get(0);
                    RoomVo roomVo = roomService.getVoData(tenancyRoom.getRoomId());
                    String roomInfo = roomVo.getCampusEasyVo().getName()+"*"+roomVo.getBuildingEasyVo().getName()+"*"+roomVo.getUnitEasyVo().getName()+"*"
                            +roomVo.getFloorEasyVo().getName()+"*"+roomVo.getRoomCode();
                    recordVo.setRoomInfo(roomInfo);
                    recordVo.setArea(roomVo.getArea());
                    recordVo.setLivingRoom(roomVo.getLivingRoom());
                    recordVo.setOrient(roomVo.getOrient());
                    recordVo.setOwnershipCode(roomVo.getOwnershipCode());
                    recordVo.setContacts(roomVo.getContacts());
                    recordVo.setPhone(roomVo.getPhone());
                    list.add(recordVo);
                }
            }
            pageResult.setList(list);
        }

        return HttpResult.data(pageResult);
    }

    /**
     * 用户申请报修
     */
    @Transactional
    public HttpResult<Void> repair(String token,RepairSubmitVo repairSubmit) {
        ClientUser user = clientUserService.selectByToken(token);
        if (user == null) {
            logger.warn("\t账号信息不存在", token);
            return HttpResult.fail("B0000", I18n.build("账号信息不存在"));
        }
        // 更新租房情况
        TenancyRoom tenancyRoom = tenancyRoomService.getById(repairSubmit.getTenancyRoomId());
        if (null == tenancyRoom){
            return HttpResult.fail("B0000", I18n.build("租房信息为空！"));
        }
        if(user.getId() != tenancyRoom.getUserId()){
            logger.warn("\t租房信息与用户信息不匹配", token);
            return HttpResult.fail("B0000", I18n.build("租房信息与用户信息不匹配"));
        }
        tenancyRoom.setTenancyState(6);
        AssertUtil.isTrue(tenancyRoomService.updateById(tenancyRoom), "更新失败");
        Room room = roomService.getById(tenancyRoom.getRoomId());
        if(room != null){
            room.setUseState(3);
            AssertUtil.isTrue(roomService.updateById(room), "更新失败");
        }
        Repair repair = new Repair();
        BeanUtils.copyProperties(repairSubmit, repair);
        repair.setRepairerUserId(tenancyRoom.getUserId());
        repair.setRoomId(tenancyRoom.getRoomId());
        repair.setRepairTime(LocalDateTime.now());
        repair.setExamineState(0);
        repair.setRepairState(0);
        AssertUtil.isTrue(repairService.save(repair), "新增失败");

        SqueryWapper squeryWapperProcess = new SqueryWapper<>(Process.class);
        QueryWrapper<Process> wrapper = Wrappers.query();
        List<String> f = new ArrayList<>();
        f.add("examineType-eq~3");
        squeryWapperProcess.setWhere(f, wrapper);
        List<Process> list = processService.list(wrapper);
        if(list.size() <= 0){
            System.out.println("===============1维修审批流程为空！");
            return HttpResult.fail("B0000", I18n.build("维修审批流程为空！"));
        }
        SqueryWapper squeryWapper = new SqueryWapper<>(Repair.class);
        QueryWrapper<Repair> wrapper1 = Wrappers.query();
        List<String> f1 = new ArrayList<>();
        f1.add("tenancyRoomId-eq~"+tenancyRoom.getId());
        f1.add("repairerUserId-eq~"+tenancyRoom.getUserId());
        f1.add("examineState-eq~0");
        f1.add("repairState-eq~0");
        List<String> orderBy = new ArrayList<>();
        orderBy.add("-repairTime");
        squeryWapper.setWhere(f1, wrapper1);
        squeryWapper.setOrderBy(orderBy, wrapper1);
        List<Repair> list1 = repairService.list(wrapper1);

        ProcessApply apply = new ProcessApply();
        apply.setTenancyRoomId(tenancyRoom.getId());
        apply.setRepairId(list1.get(0).getId());
        apply.setUserId(user.getId());
        apply.setUserName(user.getUserName());
        apply.setProcessId(list.get(0).getId());
        apply.setProcessName(list.get(0).getProcessName());
        return processApplyService.applyExamine(apply);
    }


    /**
     * 用户报修记录
     */
    @Transactional
    public HttpResult<PageResult<RepairVo>> repairRecord(PageQuery pageQuery, String token) {
        ClientUser user = clientUserService.selectByToken(token);
        if (user == null) {
            logger.warn("\t账号信息不存在", token);
            return HttpResult.fail("B0000", I18n.build("账号信息不存在"));
        }
        QueryParams params = new QueryParams();
        params.setFields(new ArrayList<>());
        List<String> f = new ArrayList<>();
        f.add("repairerUserId-eq~"+user.getId());
        List<String> orderBy = new ArrayList<>();
        orderBy.add("id");
        params.setF(f);
        params.setOrderBy(orderBy);

        PageResult<RepairVo> pageResult = new PageResult<>();
        List<RepairVo> list = new ArrayList<>();
        SqueryWapper<Repair> squeryWapper = new SqueryWapper<>(Repair.class);
        List<Repair> repairQuery = squeryWapper.query(repairService, pageQuery, params).getList();
        for (Repair repair : repairQuery) {
            RepairVo repairVo = new RepairVo();
            BeanUtils.copyProperties(repair, repairVo);
            RoomVo roomVo = roomService.getVoData(repair.getRoomId());
            String roomInfo = "";
            if(roomVo != null) {
                roomInfo = roomVo.getCampusEasyVo().getName()+"*"+roomVo.getBuildingEasyVo().getName()+"*"+roomVo.getUnitEasyVo().getName()+"*"
                        +roomVo.getFloorEasyVo().getName()+"*"+roomVo.getRoomCode();
            }
            repairVo.setRoomInfo(roomInfo);
            list.add(repairVo);
        }
        pageResult.setList(list);
        return HttpResult.data(pageResult);
    }

    /**
     * 待签合同详情
     */
    @Transactional
    public HttpResult<Contract> contractInfo(String token,Long tenancyRoomId) {
        ClientUser user = clientUserService.selectByToken(token);
        if (user == null) {
            logger.warn("\t账号信息不存在", token);
            return HttpResult.fail("B0000", I18n.build("账号信息不存在"));
        }
        TenancyRoom tenancyRoom = tenancyRoomService.getData(tenancyRoomId);
        if (tenancyRoom == null) {
            logger.warn("\t租房信息不存在", tenancyRoomId);
            return HttpResult.fail("B0000", I18n.build("租房信息不存在"));
        }
        if(user.getId() != tenancyRoom.getUserId()){
            logger.warn("\t租房信息与用户信息不匹配", token);
            return HttpResult.fail("B0000", I18n.build("租房信息与用户信息不匹配"));
        }
        if(tenancyRoom.getTenancyState() != 1){
            logger.warn("\t租房状态异常", tenancyRoomId);
            return HttpResult.fail("B0000", I18n.build("租房状态异常"));
        }
        if(tenancyRoom.getContractId() == null){
            logger.warn("\t租房合同信息不存在", tenancyRoomId);
            return HttpResult.fail("B0000", I18n.build("租房合同信息不存在"));
        }
        Contract contract = contractService.getById(tenancyRoom.getContractId());
        if(contract == null){
            logger.warn("\t租房合同信息不存在", tenancyRoom.getContractId());
            return HttpResult.fail("B0000", I18n.build("租房合同信息不存在"));
        }

        return HttpResult.data(contract);
    }

    /**
     * 合同签订
     */
    @Transactional
    public HttpResult<Void> contractSign(String token,Long contractId,String signUrl) {
        ClientUser user = clientUserService.selectByToken(token);
        if (user == null) {
            logger.warn("\t账号信息不存在", token);
            return HttpResult.fail("B0000", I18n.build("账号信息不存在"));
        }
        Contract contract = contractService.getById(contractId);
        if(contract == null){
            logger.warn("\t租房合同信息不存在", contractId);
            return HttpResult.fail("B0000", I18n.build("租房合同信息不存在"));
        }
        TenancyRoom tenancyRoom = tenancyRoomService.getData(contract.getTenancyId());
        if (tenancyRoom == null) {
            logger.warn("\t租房信息不存在", contract.getTenancyId());
            return HttpResult.fail("B0000", I18n.build("租房信息不存在"));
        }
        if(user.getId() != tenancyRoom.getUserId()){
            logger.warn("\t租房信息与用户信息不匹配", token);
            return HttpResult.fail("B0000", I18n.build("租房信息与用户信息不匹配"));
        }
        contract.setState(1);
        contract.setSignUrl(signUrl);
        AssertUtil.isTrue(contractService.updateById(contract), "更新失败");
        tenancyRoom.setTenancyState(8);
        AssertUtil.isTrue(tenancyRoomService.updateById(tenancyRoom), "更新失败");

        return HttpResult.success("合同签订成功");
    }

    /**
     * 用户提交基础信息表单
     */
    @Transactional
    public HttpResult<Void> applyApplicant(String token,Long collectId,Long formResultId,String name,
                                           String phone,Integer userLink,String processData) {
        ClientUser user = clientUserService.selectByToken(token);
        if (user == null) {
            logger.warn("\t账号信息不存在", token);
            return HttpResult.fail("B0000", I18n.build("账号信息不存在"));
        }
        List formContentConfigList = new ArrayList();
        SqueryWapper squeryWapper = new SqueryWapper<>(FormItem.class);
        QueryWrapper<FormItem> wrapper = Wrappers.query();
        List<String> f = new ArrayList<>();
        f.add("collectId-eq~"+collectId);
        List<String> orderBy = new ArrayList<>();
        orderBy.add("sort");
        squeryWapper.setWhere(f, wrapper);
        squeryWapper.setOrderBy(orderBy, wrapper);
        List<FormItem> list1 = formItemService.list(wrapper);
        for (FormItem item : list1) {
            formContentConfigList.add(item.getFormItemConfig());
        }

        FormResult formResult = new FormResult();
        formResult.setId(formResultId);
        formResult.setCollectId(collectId);
        formResult.setSubmitUserId(user.getId());
        formResult.setProcessData(processData);
        formResult.setFormContentConfig(formContentConfigList.toString());
        formResultService.submitUserForm(formResult,name,phone,userLink);
        return HttpResult.success();
    }

    /**
     * 生成随机盐
     */
    private static String randomSalt()
    {
        // 定义盐字符集
        String saltChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
        StringBuilder salt = new StringBuilder();
        Random random = new SecureRandom();
        for (int i = 0; i < 16; i++) {
            salt.append(saltChars.charAt(random.nextInt(saltChars.length())));
        }
        return salt.toString();
    }
}
